import config from '@/config'
import axios from 'axios'
import iView from 'view-design'
import { setToken, getToken } from '@/libs/util'
import router from '@/router'

export const baseUrl = (process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro) + 'admin/'

class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
  }

  interceptors (instance) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      const { data, status } = res
      if (data.code < 0) {
        if (data.code === -1) {
          setToken('')
          router.push({ name: 'login' })
          return false
        }
        // 系统业务级别报错
        if (data.code === -3) {
          iView.Message.error({
            content: data.msg
          })
          return Promise.reject(res)
        }
      } else {
        return { data, status }
      }
    }, error => {
      // 调试模式输出
      if (config.debug) {
        let result
        if (typeof (error.response.data) === 'string') {
          result = JSON.parse(error.response.data)
        } else {
          result = error.response.data
        }
        let traces = result.traces
        var tracesStr = ''
        for (var i in traces) {
          if (i > 10) {
            break
          }
          var trace = traces[i].trace
          var traceStr = ''
          for (var t in trace) {
            if (t > 50) {
              break
            }
            var item = trace[t]
            var itemStr = ''
            for (var m in item) {
              if (m === 'function') {
                continue
              }
              if (m === 'file' || m === 'line') {
                itemStr += (m) + '：' + item[m] + ' '
              }
            }
            if (itemStr !== '') {
              traceStr += itemStr + '<br/>'
            }
          }
          tracesStr += '<br/>追踪：' + (traces[i].file) + ' in line：' + (traces[i].line) +
                    '<br/>' +
                    "<p style='margin-left: 42px;font-size:12px;'>" + traceStr + '</p>'
        }

        iView.Message.error({
          content: "<span style='color:red;font-size:16px;font-weight:bold;'>服务端错误</span> <br/><br/><div style='width:100%;word-wrap:break-word;text-align:left;'>信息：" + (result.message) + (tracesStr) + '</div>',
          duration: 0,
          background: true,
          closable: true
        })
      }
      return Promise.reject(error)
    })
  }

  request (options) {
    const instance = axios.create()
    let apiAuth = getToken()
    // 基础头部
    let headers = {
      'App-Client-Version': 1.0,
      'App-Device-Type': 'web'
    }
    // 如果当前登录则带入token
    if (apiAuth !== false) {
      headers['App-Login-Token'] = apiAuth
    }
    // 附加自定义头部
    if (options.headers) {
      Object.assign(headers, options.headers)
    }
    options['headers'] = headers
    options['baseURL'] = this.baseUrl
    this.interceptors(instance)
    return instance(options)
  }
}
const api_axios = new HttpRequest(baseUrl)
export default api_axios
